package com.ichina.chat.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ichina.chat.dao.RobotDao;
import com.ichina.chat.util.Page;
import com.ichina.chat.vo.Robot;

@Component
@Transactional
public class RobotDaoimpl implements RobotDao {

	@Resource
	SessionFactory sessionFactory;
	private Session session = null;
	private Query query = null;
	private String hql = "";
	private int count = 0;

	public boolean addRobot(Robot robot) throws Exception {
		try {
			sessionFactory.getCurrentSession().persist(robot);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean updateRobot(Robot robot) throws Exception {
		try {
			sessionFactory.getCurrentSession().update(robot);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean delRobot(int rid) throws Exception {
		try {
			sessionFactory.getCurrentSession().delete(
					sessionFactory.getCurrentSession().load(Robot.class, rid));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Robot> getAll(String keyCode, Page page, int typeid)
			throws Exception {
		session = sessionFactory.getCurrentSession();
		hql = "from Robot where title like ? and typeid=?";
		query = session.createQuery(hql);
		query.setString(0, keyCode + "%");
		query.setInteger(1, typeid);
		query.setFirstResult(
				page.getPagecode() * page.getPagesize() - page.getPagesize())
				.setMaxResults(page.getPagesize()).list();
		return query.list();
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Robot> getAnswer(String keyCode,int typeid)throws Exception{
		session = sessionFactory.getCurrentSession();
		hql = "from Robot where title like ? and typeid=?";
		query = session.createQuery(hql);
		query.setString(0, keyCode + "%");
		query.setInteger(1, typeid);
		List<Robot> list = query.list();
		return list;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public int getCount(String keyCode) throws Exception {
		session = sessionFactory.getCurrentSession();
		hql = "from Robot where title like ?";
		query = session.createQuery(hql);
		query.setString(1, keyCode + "%");
		return query.list().size();
	}

}
